/**
 * 
 */
package com.ruyipu.forum.base;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

/**
 * @author donald
 *
 */
public class ImageService {
	public static final String TAG = ImageService.class.getSimpleName();
	public static final String NAME = ImageService.class.getName();
	
	public static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
	
	private ImageService(){}
	
	public static Bitmap loadImage(String imageUrl, ImageCallback imageCallback) {
		new ImageDownloader(imageUrl, imageCallback).execute("");
		return null;
	}
	
	private static class ImageDownloader extends AsyncTask<Object, Object, Bitmap> {
		private String url;
		private ImageCallback imageCallback;
		public ImageDownloader(String url, ImageCallback imageCallback) {
			this.url = url;
			this.imageCallback = imageCallback;
		}
		
		@Override
		protected Bitmap doInBackground(Object... params) {
			if(imageCache.containsKey(url)) {
				return imageCache.get(url).get();
			}
			Bitmap bitmap = loadImageFromLocal(url);
			if(null == bitmap) {
				bitmap = loadImageFromUrl(url);
			}
			imageCache.put(url, new SoftReference<Bitmap>(bitmap));
			return bitmap;
		}
		
		@Override
		protected void onPostExecute(Bitmap bitmap) {
	         imageCallback.imageLoaded(bitmap, url);
	     }
		
	}
	
	public interface ImageCallback {
		public void imageLoaded(Bitmap imageBitmap, String imageUrl);
	}
	
	/**
	 * 从网络地址加载图片
	 * 
	 * @param url
	 *            图片网址
	 * @return Bitmap
	 */
	public static Bitmap loadImageFromUrl(String url) {
		MyLog.i(TAG, "Load image : " + url);
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			MyLog.e(TAG, e1.toString());
			return null;
		} catch (IOException e) {
			MyLog.e(TAG, e.toString());
			return null;
		}
		Bitmap b = BitmapFactory.decodeStream(i);
		return b;
	}
	
	/**
	 * 保存图片文件
	 * 
	 * @param bm
	 *            图片资源
	 * @param sFile
	 *            文件名
	 * @throws IOException
	 */
	public static void saveImage(Bitmap bm, String filePath) throws IOException {
		if (bm == null || filePath == null) {
			return;
		}
		
		File myFile = new File(filePath);

		if (myFile.exists()) {
			myFile.delete();
		}

		if (!myFile.exists()) {
			FileOutputStream fout = new FileOutputStream(myFile);
			BufferedOutputStream bos = new BufferedOutputStream(fout);
			bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
			bos.flush();
			bos.close();
		}
	}
	
	/**
	 * 从本地缓存加载图片
	 * 
	 * @param url
	 *            图片网址
	 * @return Bitmap 图片
	 */
	private static Bitmap loadImageFromLocal(String url) {
		url = urlToPath(url);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 1;
		Bitmap bitmap = BitmapFactory.decodeFile(url, options);
		MyLog.i(TAG, "Load local image : " + url);
		return bitmap;
	}
	
	/**
	 * 将地址转换为文件名
	 * 
	 * @param url
	 * @return
	 */
	private static String urlToName(String url) {
		return MD5.getMD5(url.getBytes()).substring(0, 6) + ".png";
	}
	
	/**
	 * 将地址转换为绝对路径
	 * 
	 * @param url 图片网址
	 * @return String
	 */
	private static String urlToPath(String url) {
		url = urlToName(url);
		return Constants.DIR_IMAGE + url;
	}
}
